package com.uduemc.biso.node.web.api.controller.noauthentication;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.utils.CryptoJava;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.SitePathUtil;
import com.uduemc.biso.node.web.api.exception.NotFoundException;
import com.uduemc.biso.node.web.api.service.HostService;
import com.uduemc.biso.node.web.api.service.RepertoryService;
import com.uduemc.biso.node.web.utils.VideoUtil;

@RequestMapping("/api/video")
@Controller
public class ApiVideoController {

	@Autowired
	private RepertoryService repertoryServiceImpl;

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private HostService hostServiceImpl;

	@GetMapping("/repertory/{hostsecret}/{secret}")
	public void repertoryVideo(@PathVariable("hostsecret") String hostsecret, @PathVariable("secret") String secret, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		secret = secret.substring(0, secret.lastIndexOf("."));
		String de = CryptoJava.de(secret);
		String hostDe = CryptoJava.de(hostsecret);
		int id = 0;
		int hostId = 0;
		if (de != null) {
			try {
				hostId = Integer.valueOf(hostDe);
				id = Integer.valueOf(de);
			} catch (NumberFormatException e) {
			}
		}
		if (id < 1 || hostId < 1) {
			throw new NotFoundException("repertoryVideo 未能获取到id以及hostId数据！");
		}
		HRepertory hRepertory = repertoryServiceImpl.getInfoByid(id);
		if (hRepertory == null || hRepertory.getType().shortValue() != 5 || hRepertory.getHostId().longValue() != hostId) {
			throw new NotFoundException("repertoryVideo 未能获取到hRepertory数据！");
		}

		String uri = request.getRequestURI();
		String substring = uri.substring(uri.lastIndexOf(".") + 1);
		if (!substring.equals(hRepertory.getSuffix())) {
			throw new NotFoundException("repertoryVideo 获取到hRepertory数据与实际中的后缀不符！");
		}

		String basePath = globalProperties.getSite().getBasePath();

		Host host = hostServiceImpl.getInfoById(hRepertory.getHostId());

		// 通过 basePath 以及 code 获取 用户的目录
		String userPathByCode = SitePathUtil.getUserPathByCode(basePath, host.getRandomCode());
		String filepath = hRepertory.getFilepath();
		String filefullpath = userPathByCode + "/" + filepath;

		File file = new File(filefullpath);// 得到文件
		if (!file.isFile()) {
			throw new NotFoundException("repertoryVideo 获取到hRepertory数据，实际视频图片文件地址不存在！filefullpath：" + filefullpath);
		}

		VideoUtil.play(filefullpath, request, response);

	}

}
